//
//  AppDelegate+UMessage.m
//  xk100
//
//  Created by xiaokang on 2017/5/2.
//  Copyright © 2017年 xiaokang. All rights reserved.
//


static NSString *const UMengAppKey = @"58bfc4217f2c747688001063";


#import "AppDelegate+UMessage.h"

@implementation AppDelegate (UMessage)
- (void)startUmengMessageWithLaunchOptions:(NSDictionary *)launchOptions {
    
    [UMessage startWithAppkey:UMengAppKey launchOptions:launchOptions httpsEnable:YES];
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions types10 = UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            
        } else {
            //点击不允许
            
        }
    }];
    
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSLog(@"收到远程推送");
    [UMessage didReceiveRemoteNotification:userInfo];
    
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"前台远程通知");
        [UMessage setAutoAlert:NO];
        [UMessage didReceiveRemoteNotification:userInfo];
        
        
    } else {
        NSLog(@"前台本地通知");
        
    }
    
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}


//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"后台远程通知");
        [UMessage didReceiveRemoteNotification:userInfo];
        
        NSString *string = userInfo[@"content"];
        if ([string isValidUrl]) {
            
            if (SYSTEM_VERSION_LESS_THAN(@"10")) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string] options:@{} completionHandler:nil];
            }
        }
        
    } else {
        NSLog(@"后台本地通知");
        
        
    }
    
}


@end
